package com.ssb.plugins;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apache.cache.util.Validator;
import com.apache.exception.BusinessException;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.MD5Utils;
import com.apache.tools.StrUtil;
import com.ssb.service.check.CheckedFrontSysService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 黄河接口对接-电子保单获取
 */
@Component
public class HheSelectRlectronicPolicy extends HheSuperPlugin {

    @Autowired
    private CheckedFrontSysService checkedFrontSysService;

    @Override
    public Object beforeInvoke(Map<String, Object> map) {
        //校验此前端系统是否存在且有效
        String frontSysCode = StrUtil.doNull(String.valueOf(map.get("frontSysCode")));
        Map<String,String> result =  checkedFrontSysService.checkedSysByFrontSysCode(frontSysCode);
        if (result.get("errorCode").equals("F")){
            throw new BusinessException("此系统有误：" + result.get("errorMsg"));
        }
        String infoId=String.valueOf(map.get("infoId"));
        if(StrUtil.isNull(infoId)){
            throw new BusinessException("订单ID不能为空");
        }
        Object obj = getOrderById(infoId);
        if(!Validator.isEmpty(obj)){
            map.put("orderInfo",obj);
            customMethod(map);
        }
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> map) {
        customMethod(map);
        return null;
    }

    private void customMethod(Map<String, Object> map) {
        long startLong = System.currentTimeMillis();
        Map<String, Object> param = new HashMap<>();
        Map<String, Object> head = new HashMap<>();
        Map<String, Object> body = new HashMap<>();
        DataMap orderInfo = (DataMap)map.get("orderInfo");
        head.put("platform",StrUtil.doNull(String.valueOf(orderInfo.get("channelId")),"SSK"));//平台标示（默认与渠道编码一致）
        head.put("requestType","30");//请求类型（10：投保单：30：电子保单；40：保单生成通知，50：电子发票）
        String transactionNo = Validator.generate();
        head.put("transactionNo",transactionNo);//请求事务编号，用于区别是那一次的请求
        head.put("md5Value", "");//32位的编码结果, 另外约定的密码 进行MD5编码 可空
        head.put("timeStamp", DateUtils.Now.fmt_yyyyMMdd_HHmmss());//时间戳
        head.put("errorCode","0000");//0000：成功
        head.put("errorMsg","成功");//错误描述，无异常返回“成功”（默认成功）
        boolean mark = StrUtil.isNotNull(String.valueOf(orderInfo.get("policyDownUrl")));
        Map<String, Object> inv = new HashMap<>();
        inv.put("policyNo",orderInfo.get("policyNo"));//保单号
        inv.put("errorCode","0000");//0000：成功；
        inv.put("errorMsg","成功");//错误原因,无错误返回“成功”
        if(mark){
            inv.put("policyDownUrl",String.valueOf(orderInfo.get("policyDownUrl")));
        }
        List<Map> list = new ArrayList<>();
        list.add(inv);
        body.put("insResults",list);

        param.put("head",head);
        param.put("body",body);
        if(mark){
            map.put("resultData",param);
            return ;
        }
        String str = String.valueOf(sendInterface("Externalcommon/surrenderSSK", param,null));
        log.info("电子保单获取结果："+str);
        if(Validator.isNotNull(str)) {//处理接口返回结果
            JSONObject json = JSON.parseObject(str);
            if(json.containsKey("body")) {
                JSONArray array = json.getJSONObject("body").getJSONArray("insResults");
                for (int i = 0; i < array.size(); i++) {
                    JSONObject obj = array.getJSONObject(i);
                    if ("0000".equals(obj.getString("errorCode"))) {
                        String editSql ="update ss_insur_order set policy_down_url='"+obj.getString("policyDownUrl")+"' where info_id='"+orderInfo.get("infoId")+"' ";
                        IusPluginUtil.getInstance().saveInvoke(DATA_SOURCE,editSql);
                    }
                }
            }
            map.put("resultData",json);
        }
        log.info("huanghe policy_down_url interface exetime = "+(System.currentTimeMillis()-startLong)+" ms");
    }
}
